<?php
namespace app\api\controller;


use app\api\model\UserModel;
use think\Controller;

class User extends Controller
{
    /**
     * @title 登陆接口
     * @author hehecat
     * @moudle 用户模块
     *
     * @param username type:string desc:用户名
     * @param password type:string desc:密码
     * @return id desc:用户id 失败返回0
     */
    function login() {
        $username = input('get.username');
        $password = input('get.password');

        $model = new UserModel();
        $result = $model->login($username,$password);
        if ($result) {
            session_start();
            $sessionid = session_id();
            $redis = getRedis();
            $redis->set($result['userid'],$sessionid);
           return json_encode(['sessionid'=>$sessionid, 'userid'=>$result['userid']]);
        }else {
            return  json_encode(['id'=>0]);
        }
    }


    function repassword() {
        $userid = input('get.userid');
        $sessionid = input('get.sessionid');
        $oldpassword = input('get.oldpassword');
        $newpassword = input('get.newpassword');

        $redis = getRedis();
        if ($sessionid!='' && $sessionid == $redis->get($userid)) {
            $model = new UserModel();
            $result = $model->repassword($userid,$oldpassword,$newpassword);
            return json_encode($result);
        }
        return  json_encode(['error'=>'sessionid无效']);
    }


    function updatenickname() {
        $userid = input('get.userid');
        $nickname = input('get.nickname');
        $sessionid = input('get.sessionid');

        $redis = getRedis();
        if ($sessionid!='' && $sessionid == $redis->get($userid)) {
            $model = new UserModel();
            $result = $model->updateNickname($userid,$nickname);
            return json_encode($result);
        }
        return  json_encode(['error'=>'sessionid无效']);
    }


    function updateavatar() {

        $userid = input('post.userid');
        $sessionid = input('post.sessionid');

        $redis = getRedis();
        if ($sessionid!='' && $sessionid == $redis->get($userid)) {
            $file = request()->file('image');
            if($file){
                $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
                if($info){ //上传成功
                    $model = new UserModel();
                    $result = $model->updateAvatar($userid,$info->getSaveName());
                    return json_encode($result);
                }else{
                    // 上传失败获取错误信息
                    return json_encode(['error'=>$file->getError()]);
                }
            }
        }
        return  json_encode(['error'=>'sessionid无效']);
    }

}